package org.example.demo.util;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class RequestUtil {
    private RestTemplate restTemplate;
    final String wxAPI = "https://api.weixin.qq.com/sns/jscode2session";
    final String grant_type = "authorization_code";

    public String requestOpenId(String loginCode, String AppId, String AppSecret) {
        String sb = this.wxAPI + "?appid={AppId}&secret={AppSecret}&js_code={loginCode}&grant_type={grant_type}";

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("AppId", AppId);
        paramMap.put("AppSecret", AppSecret);
        paramMap.put("loginCode", loginCode);
        paramMap.put("grant_type", grant_type);

        try {
            restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(sb, String.class, paramMap);
            if (response.getStatusCodeValue() == 200) {
                return response.getBody();
            }
        } catch (NullPointerException e) {
            System.out.println("获取wxopenid失败");
        }
        return "";
    }
}
